
class Admin::FloorsController < Admin::BaseController

  before_action :find_floor, only: [:show, :edit, :update, :destroy]

  def index
    @floors = Floor.paginate(page: params[:page] || 1, per_page: params[:per_page] || 15).order("id desc")
  end

  def show
    respond_to do |format|
       format.json { render json: {status: 'ok', floor: @floor}}
     end
  end

  def new
    @floor = Floor.new
    @categories = Category.get_floor_category.children
  end

  def create
    floor_params = params.require(:floor).permit!
    floor_params[:product_ids] = floor_params[:product_ids].split(',')
    @floor = Floor.new(floor_params)
    if @floor.save
      flash[:notice] = "新建楼层成功"
      redirect_to admin_floors_path
    else
      flash[:notice] = "新建楼层失败"
      render action: :new
    end
  end

  def edit
    @categories = Category.get_floor_category.children
    render action: :new
  end

  def update
    floor_params = params.require(:floor).permit!
    floor_params[:product_ids] = floor_params[:product_ids].split(',')
    @floor.attributes = floor_params

    if @floor.save
      flash[:notice] = "修改楼层成功"
      redirect_to admin_floors_path
    else
      flash[:notice] = "修改楼层失败"
      render action: :edit
    end
  end

  def destroy
    begin
      @floor.destroy
      flash[:notice] = "删除楼层成功"
      redirect_to admin_floors_path
    rescue
      flash[:notice] = "删除楼层失败"
      redirect_to :back
    end
  end

  private

  def find_floor
    @floor = Floor.find params[:id]
  end

end
